package com.zsxb.crm.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zsxb.crm.context.StatusContext;
import com.zsxb.crm.dto.DictDTO;
import com.zsxb.crm.dto.DictDetailDto;
import com.zsxb.crm.dto.DictDetailPageDto;
import com.zsxb.crm.dto.DictPageDTO;
import com.zsxb.crm.enumeration.ResultCodeEnum;
import com.zsxb.crm.exception.BaseException;
import com.zsxb.crm.mapper.DictMapper;
import com.zsxb.crm.mapper.SysStatusMapper;
import com.zsxb.crm.pojo.Dict;
import com.zsxb.crm.pojo.SysStatus;
import com.zsxb.crm.result.PageResult;
import com.zsxb.crm.service.DictService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DictServiceImpl implements DictService {
    @Autowired
    private DictMapper dictMapper;
    @Autowired
    private SysStatusMapper sysStatusMapper;


    /**
     * 数据字典分页
     */
    @Override
    public PageResult pageQuery(DictPageDTO dictPageDTO) {
        PageResult pageResult = new PageResult();
        if (dictPageDTO.getPageNum() != null && dictPageDTO.getPageSize() != null) {
            PageHelper.startPage(dictPageDTO.getPageNum(), dictPageDTO.getPageSize());
            //处理数据
            if (dictPageDTO.getParams() != null) {
                String beginTime = dictPageDTO.getParams().get("beginTime").toString();
                dictPageDTO.setBeginTime(beginTime);
                String endTime = dictPageDTO.getParams().get("endTime").toString();
                dictPageDTO.setEndTime(endTime);
            }
            Page<Dict> dictList = (Page<Dict>) dictMapper.pageQuery(dictPageDTO);
            pageResult.setTotal(dictList.getTotal());
            pageResult.setRows(dictList.getResult());
        } else {
            List<Dict> dicts = dictMapper.pageQuery(dictPageDTO);
            Long total = dictMapper.countTotal();
            pageResult.setTotal(total);
            pageResult.setRows(dicts);
        }
        return pageResult;
    }

    /**
     * 字典类型新增
     */
    @Override
    public void insert(DictDTO dictDTO) {

        Dict dict = new Dict();
        BeanUtils.copyProperties(dictDTO, dict);
        dictMapper.insert(dict);
    }

    /**
     * 字典类型删除
     */
    @Override
    @Transactional
    public void delete(String dictIds) {
        String[] split = dictIds.split(",");
        List<Dict> dictList = dictMapper.findByIds(split);
        log.info("dictList:{}" ,dictList);
        //根据状态
        for (Dict dict : dictList) {
            if (dict.getStatus().equals(StatusContext.DISABLE.toString())){
                throw new BaseException(ResultCodeEnum.STATUS_IS_ENABLE);
            }
        }
        List<String> collect = dictList.stream().map(Dict::getDictType).collect(Collectors.toList());
        List<SysStatus> sysStatusList = sysStatusMapper.findByDictTypes(collect);
        log.info("sysStatusList:{}" ,sysStatusList);
        //有无字典数据
        if (sysStatusList.size()>0){
            throw new BaseException(ResultCodeEnum.HAVE_DICT_DETAIL);
        }
        dictMapper.delete(split);
    }

    @Override
    public void deleteDetail(String dictCode) {
        String[] split = dictCode.split(",");
        List<SysStatus> list = sysStatusMapper.findByIds(split);
        for (SysStatus sysStatus : list) {
            if (sysStatus.getStatus().equals(StatusContext.DISABLE.toString())){
                throw new BaseException(ResultCodeEnum.STATUS_IS_ENABLE);
            }
        }
        //TODO 删除条件待加
        sysStatusMapper.deleteByIds(split);
    }
    /**
     * 字典类型修改回显
     */
    @Override
    public Dict queryByDictId(Long dictId) {
        return dictMapper.queryByDictId(dictId);
    }

    /**
     * 字典类型修改回显
     */
    @Override
    @Transactional
    public void update(Dict dict) {
        Dict isExist = dictMapper.findById(dict.getDictId());
        dictMapper.update(dict);
        Dict selectById = dictMapper.findById(dict.getDictId());
        if (!isExist.equals(selectById)) {
            List<Dict> list = dictMapper.findAll();
            List<Dict> collect1 = list.stream().filter(o -> o.getDictName().equals(dict.getDictName())).collect(Collectors.toList());
            List<Dict> collect2 = list.stream().filter(o -> o.getDictType().equals(dict.getDictType())).collect(Collectors.toList());
            if (collect1.size() > 1 || collect2.size() > 1) {
                throw new BaseException(ResultCodeEnum.DICT_DETAIL_EXIST);
            }
        }
    }


    @Override
    public List<SysStatus> findByDictType(String dictType) {
        Dict dict = dictMapper.findByDictType(dictType);
        if (dict == null) {
            throw new BaseException(ResultCodeEnum.DICT_TYPE_ERROR);
        }
        List<SysStatus> list = sysStatusMapper.findByDictType(dictType);
        return list;
    }

    @Override
    public PageResult findDetailByDictType(DictDetailPageDto dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        Page<SysStatus> list = sysStatusMapper.findByCondition(dto);
        return new PageResult(list.getTotal(), list.getResult(), null);
    }

    @Override
    public void addDictDetail(DictDetailDto dto) {
        chackDictValueAndLabel(dto);
        SysStatus sysStatus = new SysStatus();
        BeanUtils.copyProperties(dto, sysStatus);
        sysStatus.setIsDefault(StatusContext.NO_DEFAULT);
        sysStatusMapper.insert(sysStatus);
    }

    @Override
    @Transactional
    public void updateDictDetail(SysStatus dto) {
        SysStatus isExist = sysStatusMapper.selectById(dto.getDictCode());
        sysStatusMapper.updateById(dto);
        SysStatus selectById = sysStatusMapper.selectById(dto.getDictCode());
        if (!isExist.equals(selectById)) {
            List<SysStatus> byDictType = sysStatusMapper.findByDictType(dto.getDictType());
            List<SysStatus> collect1 = byDictType.stream().filter(o -> o.getDictLabel().equals(dto.getDictLabel())).collect(Collectors.toList());
            List<SysStatus> collect2 = byDictType.stream().filter(o -> o.getDictValue().equals(dto.getDictValue())).collect(Collectors.toList());
            if (collect1.size() > 1 || collect2.size() > 1) {
                throw new BaseException(ResultCodeEnum.DICT_DETAIL_EXIST);
            }
        }
    }

    @Override
    public SysStatus findByDictCode(Long dictCode) {
        return sysStatusMapper.selectById(dictCode);
    }



    private void chackDictValueAndLabel(DictDetailDto dto) {
        List<SysStatus> byDictType = sysStatusMapper.findByDictType(dto.getDictType());
        SysStatus sysStatus1 = byDictType.stream().filter(o -> o.getDictLabel().equals(dto.getDictLabel())).findFirst().orElse(null);
        SysStatus sysStatus2 = byDictType.stream().filter(o -> o.getDictValue().equals(dto.getDictValue())).findFirst().orElse(null);
        if (sysStatus1 != null || sysStatus2 != null) {
            throw new BaseException(ResultCodeEnum.DICT_DETAIL_EXIST);
        }

    }




}
